#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "search.h"

static int get_word(FILE *fp,char *desc,char *key)
{
	int i,j;
	char buf[BUF_SIZE];
	char *retp;
//fgets:一次读取一行
	retp = fgets(buf,BUF_SIZE,fp);
	if(retp == NULL)
		return -1;
	for(i = 0;i < KEY_SIZE-1 && buf[i] != ':';i++)
		key[i] = buf[i];
	key[i] = '\0';
	
	for(i++,j = 0;j < DESC_SIZE-1 && buf[i] != '\0';i++,j++)
		desc[j] = buf[i];
	desc[j] = '\0';
	return 0;
}

	int insert(tree_st **ptr,char *key,char *desc)
{
	if(*ptr == NULL)
	{
		int i;
		tree_st *newnode;
		newnode = malloc(sizeof(*newnode));
			if(newnode == NULL)
				return -1;
		for(i = 0;i < Max;i++)
			newnode->arr[i] = NULL;
		for(i = 0;i < DESC_SIZE;i++)
			newnode->desc[i] = '\0';
		*ptr = newnode;
	}
		if(*key == '\0')
		{
			strcpy((*ptr)->desc,desc);
			return 0;
		}

		insert((*ptr)->arr + *key - 'a',key+1,desc);
}

	tree_st *find(tree_st *ptr,char *key)
{
	if(ptr == NULL)
		return NULL;
	if(*key == '\0')
		return ptr;
	return find(ptr->arr[*key-'a'],key+1);
}


void read()
{
	FILE *fp;
	tree_st *tree = NULL;
	int ret = 0;
	char desc[DESC_SIZE],key[KEY_SIZE];
	fp = fopen(FILENAME,"r");
	if(fp == NULL)
	{
		//fprintf(stderr,"fopen():%s\n",strerror(errno));
		perror("fopen()");
		exit(1);
	}

	while(1)
	{
		ret = get_word(fp,desc,key);
		if(ret == -1)
			break;
		insert(&tree,key,desc);	
	}
	tree_st *p = NULL;
	p = find(tree,"Cat");
	if(p)
		printf("%s",p->desc);
	fclose(fp);
	
}
